package com.yswy.common.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ImageCompression {
    public static void main(String[] args) {
        String inputImagePath = "path/to/input/image.jpg";
        String outputImagePath = "path/to/output/image.jpg";

        try {
            compressImage(inputImagePath, outputImagePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void compressImage(String inputImagePath, String outputImagePath) throws IOException {
        Path inputPath = Paths.get(inputImagePath);
        Path outputPath = Paths.get(outputImagePath);

        // 读取输入图像
        BufferedImage inputImage = ImageIO.read(inputPath.toFile());

        // 获取输入图像的格式
        String format = Files.probeContentType(inputPath);

        // 如果输入图像的格式是 JPEG 或 PNG，则使用相同的格式进行输出
        if (format != null && (format.endsWith("jpeg") || format.endsWith("jpg"))) {
            format = "jpg";
        } else if (format != null && format.endsWith("png")) {
            format = "png";
        } else {
            throw new IllegalArgumentException("Invalid image format: " + format);
        }

        // 将无损压缩后的图像写入输出文件
        ImageIO.write(inputImage, format, new File(outputImagePath));
    }
}